package com.example.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * TODO: 这里要写注释的!
 */
public class FactorialCalculatorMain {
    public static void main(String[] args) {
        ThreadPoolExecutor executor= (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        List<Future<Integer>> futureList= new ArrayList<>();
        Random random= new Random();
        for (int i = 0; i <10; i++) {
            Integer number= random.nextInt(10);
            FactorialCalculator calculator= new FactorialCalculator(number);
            Future<Integer> result= executor.submit(calculator);
            futureList.add(result);
        }
        do{
            System.out.printf("main: number of complete tasks: %d\n",executor.getCompletedTaskCount());
            for (int i = 0; i < futureList.size(); i++) {
                Future<Integer> future= futureList.get(i);
                System.out.printf("main: task %d: %s\n",i,future.isDone());
            }
            try {
                TimeUnit.MILLISECONDS.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }while (executor.getCompletedTaskCount()<futureList.size());

        System.out.printf("main: results\n");
        for (int i = 0; i < futureList.size(); i++) {
            Future<Integer> future= futureList.get(i);
            Integer number= null;
            try {
                number= future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.printf("main: task %d: %d\n",i,number);
        }
        executor.shutdown();
    }
}
